package com.ai.wx.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.wx.service.CoreService;
import com.ai.wx.util.SignUtil;

@Controller
public class WxCoreController {

	@RequestMapping(value = "/wx", method = RequestMethod.GET)
	@ResponseBody
	public String doGetFromWx(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request) throws UnsupportedEncodingException {
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			return echostr;
		}
		return "";
	}

	@RequestMapping(value = "/wx", method = RequestMethod.POST, produces = "application/xml;charset=UTF-8")
	@ResponseBody
	public String doPostFromWx(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败

        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
		String respMessage = CoreService.processRequest(request);
		return respMessage;
	}
}
